<!--用户管理-->
<template>
  <div class="page-container">
    <page_breadcrumb :getKeyMethod="init_table_model" @change="change_table_model" pageOption />

    <ex_super_table_page v-bind="option" ref="SuperTablePage" @selection-change="e => selection = e">
    </ex_super_table_page>

    <ex_super_dialog_form ref="auditDialog" v-bind="auditDialog" @afterSubmitSuccess="reload()">
    </ex_super_dialog_form>

  </div>
</template>
<script>

let moduleName = "label_fms_bill_list_customer_bill_manager"

import superTablePageFunction from '@/mixin/super-table-page-function';
import page_table_model_manage from '@/mixin/page_table_model_manage';

export default {

  title: moduleName,
  components: {},

  mixins: [superTablePageFunction, page_table_model_manage],
  data() {


    return {
      selection: [],


      option: {
        search: {
          model: [
            { label: "label_fms_subject_bill_number", key: "billNo", attrs: { clearable: true } },
            {
              label: "label_fms_account_cmp_customer", key: "customerId", type: 'common_customer_choose', attrs: { multiple: false, },
            },
            {
              label: "label_status", key: "status", type: 'select', enum: 'FmsBillStatusEnum', attrs: { clearable: true }
            },
            {
              key: 'accountType', label: 'label_fms_bill_list_pay_account', type: 'select', enum: 'CustomerAccountTypeEnum',
            },
          ],
        },
        actionExtra: [
        {
            label: 'label_fms_bill_list_business_review',auth:"fms_income_bill_list_business_review", attrs: { type: "primary" }, click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
              if(!this.selection.some(row=>['BIZ_CONFIRM', 'FMS_REFUSE'].includes(row.status))){
                return this.$message.error(this.$t("tip_part_order_status_error_no_operate"))
              }
              this.batchAudit(this.selection)
            }
          },
          {
            label: 'label_fms_bill_list_financial_review',auth:"fms_income_bill_list_financial_review", attrs: { type: "primary" }, click: () => {
              if (_.isEmpty(this.selection)) return this.$message.error(this.$tt('tip_please_select_order'))
              if(!this.selection.some(row=>['FMS_CONFIRM'].includes(row.status))){
                return this.$message.error(this.$t("tip_part_order_status_error_no_operate"))
              }
              this.batchAudit(this.selection)
            }
          },

          { label: 'label_export', attrs: { type: "primary" }, click: this.exportExcel },
        ],

        table: {
          url: "/fms-api/customer/CustomerBillRpc/select.json",
          attrs: {
            'cell-style': ({ row, column, rowIndex, columnIndex }) => {
              if (column.property == 'status') {
                return { color: row.status == 'NORMAL' ? this.$globalCss.successColor : this.$globalCss.infoColor }
              }
            }
          },
          model: this.init_table_model(),

        }
      },
      auditDialog: {
        customClass: 'dialog_auto',
        submitUrl: '/fms-api/customer/CustomerBillRpc/fms_audit.json',
        submitDataHandle: (data) => {
          if (data.type != 'FAIL') data.failMessage = null
          return {
            id: data.id, 'billId': data.id,
            type: data.type,
            failMessage: data.failMessage,
          }
        },
        form: {
          itemClass: "form_item_default", inputClass: "form_input_default",
          model: [
            { header: "label_fms_account_log_apply_info", },
            {
              key: 'customerName', label: 'label_fms_account_cmp_as_customer',
              render: (h, { data, item }) => this.$renderText(h, this.$formatNameCode(data.customerName, data.customerCode))
            },
            {
              key: 'productType', label: 'label_fms_account_apply_account_category',
              render: (h, { data, item }) => {
                const value = []
                if (data.productType) {
                  value.push(this.$enumShow(data.productType, 'PmsProductTypeEnum'))
                }
                if (data.currencyType) {
                  value.push(this.$enumShow(data.currencyType, 'CurrencyTypeEnum'))
                }
                if (data.accountType) {
                  value.push(this.$enumShow(data.accountType, 'CustomerAccountTypeEnum'))
                }
                return this.$renderText(h, value.join(" - "))
              }
            },
            {
              key: 'happenTime', label: 'label_fms_bill_list_bill_date',
              render: (h, { data, item }) => this.$renderText(h, this.$dateFormat(data[item.key]))
            },

            {
              key: 'billNo', label: 'label_fms_subject_bill_number',
              render: (h, { data, item }) => this.$renderText(h, data[item.key])
            },
            {
              key: 'billPeriod', label: 'label_fms_subject_bill_period',
              render: (h, { data, item }) => this.$renderText(h, data[item.key])

            },
            {
              key: 'amount', label: 'label_fms_subject_bill_amount',
              render: (h, { data, item }) => this.$renderText(h, data[item.key])

            },




            { header: "label_fms_account_log_examine_result", },
            {
              key: 'type', label: 'label_fms_account_log_examine_result', type: 'radio-group',
              attrs: {
                i18n: true,
                items: [
                  { label: 'label_fms_account_log_examine_success', value: 'DONE' },
                  { label: 'label_fms_account_log_examine_fail', value: 'FAIL' }
                ],
              }
            },
            { key: 'failMessage', label: 'label_fms_account_log_examine_fail_reason', if: (data) => data.type == 'FAIL' },

          ],
          rules: {
            'type': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],
            // 'refuseReason': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'change' }],

          },
        }
      },

    };
  },





  methods: {
    option_table_model() {
      return [
        { type: 'selection', clickToggle: true, keyGroup: 'label_table_operate' },
        { key: 'billNo', label: 'label_fms_subject_bill_number', align: 'center' },
        {
          key: 'companyName', label: 'label_customer_name', align: 'left', attrs: {
            formatter: (r, c, v, i) => {
              return '[' + r.customerCode + '] ' + r.customerName
            }
          }
        },
        { key: 'billPeriod', label: 'label_fms_subject_bill_period', align: 'center' },
        {
          key: 'accountType', label: 'label_fms_bill_list_pay_account', width: 200,
          attrs: {
            formatter: (r, c, v, i) => {
              return (r.accountType == 'CREDIT' ? (this.$enumShow(r.productType, 'PmsProductTypeEnum') + '-') : '') + this.$enumShow(r.currencyType, 'CurrencyTypeEnum') + '-' + this.$enumShow(r.accountType, 'CustomerAccountTypeEnum')
            }
          }
        },
        {
          key: 'happenTime', label: 'label_fms_bill_list_bill_date', width: 160, attrs: {
            formatter: (r, c, v, i) => {
              return this.$dateFormat(v)
            }
          }
        },

        { key: 'amount', label: 'label_fms_subject_bill_amount', align: 'center' },
        {
          key: 'currencyType', label: 'label_currency_kind',
          attrs: {
            formatter: (r, c, v, i) => {
              return this.$enumShow(v, 'CurrencyTypeEnum')
            }
          }
        },
        { key: 'payAmount', label: 'label_fms_bill_list_settled_amount', align: 'center' },
        { key: 'ticketAmount', label: 'label_fms_bill_list_reissued_amount', align: 'center' },

        {
          key: 'status', label: 'label_fms_account_apply_status',
          width: 120,
          attrs: {
            formatter: (r, c, v, i) => {
              return this.$enumShow(v, 'FmsBillStatusEnum')
            }
          }
        },
        {
          type: 'operate', width: 220, fixed: 'right',
          operate: [

            // 业务复核
            {
              if: (row) => ['BIZ_CONFIRM', 'FMS_REFUSE'].includes(row.status),
              auth: 'fms_income_bill_list_business_review',
              label: 'label_fms_bill_list_business_review', click: (row) => {
                this.businessReview(row)
              }
            },
            // 财务复核
            {
              if: (row) => ['FMS_CONFIRM'].includes(row.status),
              auth: 'fms_income_bill_list_financial_review',

              label: 'label_fms_bill_list_financial_review', click: (row) => {
                // let tmpForm = JSON.parse(JSON.stringify(row))
                // tmpForm['type'] = 'DONE'
                // this.formValue = tmpForm
                // this.dialogFormVisible = true

                this.$refs.auditDialog.showNew({
                  title: this.$t("label_fms_bill_list_financial_audit"),
                  submitType: "form",
                  data: Object.assign({}, row, { type: "DONE" }),
                  onlySetData: true,
                })
              }
            },
            // 结算单详情
            {
              label: 'label_fms_subject_detail', click: (row) => {
                this.$router.push({
                  path: '/page/fms/income/bill_view',
                  query: { id: row.id, no: row.billNo }
                })
              }
            },
            ,
            // 取消
            {
              if: (row) => {
                return row.status != 'UNPAY' && row.status != 'DONE'
              },
              label: 'label_cancel', auth: 'fms_income_bill_list_cancel', click: (row) => {

                let _this = this
                let title = '确定要取消该账单吗？<br/> 账单取消后，可以针对账单下的结算单重新生成账单。'
                this.$confirm(title, this.$tt('label_tip'), {
                  dangerouslyUseHTMLString: true,
                  width: 800,
                  confirmButtonText: this.$tt('label_fms_account_config_confirm'),
                  cancelButtonText: this.$tt('label_fms_account_config_cancel'),
                  type: 'warning'
                }).then(() => {

                  _this.$ajax({
                    url: '/fms-api/customer/CustomerBillRpc/cancelBill.json',
                    data: {
                      'billId': row.id
                    },
                    success: (responseData) => {
                      _this.$message({
                        showClose: true,
                        message: '提交成功',
                        type: 'success'
                      })
                      _this.$refs['SuperTablePage'].reload()
                    }
                  });

                }).catch(() => {
                });

              }
            },

          ],
        }
      ]
    },
    batchAudit(list) {
      if (list.some(row => !['BIZ_CONFIRM', 'FMS_REFUSE', 'FMS_CONFIRM'].includes(row.status))) {
        return this.$message.error(this.$t("tip_part_order_status_error_no_operate"))
      }
      const business = list.filter(row => ['BIZ_CONFIRM', 'FMS_REFUSE'].includes(row.status))
      const bills = list.filter(row => ['FMS_CONFIRM'].includes(row.status))
      if (!_.isEmpty(business) && !_.isEmpty(bills)) {
        return this.$message.error(this.$tt("tip_only_select_some_one_kind", { type: this.$tt(['label_fms_bill_list_business_review', 'label_fms_bill_list_financial_review'], ",") }),)
      }

      const select = !_.isEmpty(business) ? business : bills
      const type = !_.isEmpty(business) ? "businessReviewNet" : "submitAuditNet"
      const paramsFun = !_.isEmpty(business) ? (row) => ({ 'billId': row.id }) : (row) => ({ id: row.id, 'billId': row.id, type: "DONE", })

      this.$confirm(this.$tt("tip_confirm_audit_select_count_order", { count: select.length }), this.$tt('label_tip'), {
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: this.$tt('tip_submiting'),
        });
        Promise.all(select.map(row => {
          return new Promise((resolve, reject) => {
            this[type](
              {
                data: paramsFun(row),
                config: {},
                success: () => {
                  resolve(true)
                },
                failure: () => {
                  resolve(false)
                }
              }
            )
          })
        })).then(resultList => {
          if (loading) loading.close();
          this.reload()
          this.$alert(`复核成功：${resultList.filter(it => it).length}; 复核失败：${resultList.filter(it => !it).length} `, this.$tt('label_tip'), {

          });
        }).catch(() => {
          if (loading) loading.close();
        });


      }).catch(() => {
      });

    },
    submitAuditNet({ data, success, failure }) {
      this.$ajax({
        url: '/fms-api/customer/CustomerBillRpc/fms_audit.json', 
        data,
        success,
        failure
      });
    },
    businessReviewNet({ data, success, failure, config }) {
      this.$ajax({
        url: '/fms-api/customer/CustomerBillRpc/biz_audit.json',
        data,
        success,
        failure,
        ...config,
      });
    },
    businessReview(row) {

      let title = ''
      title += `<div style="display: flex;"><div style="width: 90px; text-align: left;">客户</div><div> [${row.customerCode}] ${row.customerName}</div></div>`
      title += `<div style="display: flex;"><div style="width: 90px; text-align: left;">账单编号</div><div>${row.billNo}</div></div>`
      title += `<div style="display: flex;"><div style="width: 90px; text-align: left;">账单金额</div><div>${row.amount}  （${this.$enumShow(row.currencyType, 'CurrencyTypeEnum')}）</div></div>`
      title += `<div style="display: flex; color: red; "><br/>确定审核通过吗 ?</div>`

      this.$confirm(title, this.$tt('label_tip'), {
        dangerouslyUseHTMLString: true,
        width: 800,
        confirmButtonText: this.$tt('label_fms_account_config_confirm'),
        cancelButtonText: this.$tt('label_fms_account_config_cancel'),
        type: 'warning'
      }).then(() => {
        this.businessReviewNet(
          {
            data: {
              'billId': row.id
            },
            config: { loading: true },
            success: () => {
              this.$message({
                showClose: true,
                message: this.$t("tip_submit_success"),
                type: 'success'
              })
              this.$refs['SuperTablePage'].reload()
            },
            failure: () => { }
          }
        )

      }).catch(() => {
      });
    },
    exportExcel() {
      if (_.isEmpty(this.selection)) {
        this.$message({
          showClose: true,
          message: '请选择要导出的数据',
          type: 'warning'
        })
        return
      }
      // 导出账单必须为统一客户
      let customerCode = this.selection[0].customerCode
      for (let i = 0; i < this.selection.length; i++) {
        if (this.selection[i].customerCode != customerCode) {
          this.$message({
            showClose: true,
            message: '请选择同一客户的账单',
            type: 'warning'
          })
          return
        }
      }

      // 导出账单类型必须为同一种 productType
      let productType = this.selection[0].productType
      for (let i = 0; i < this.selection.length; i++) {
        if (this.selection[i].productType != productType) {
          this.$message({
            showClose: true,
            message: '请选择类型的账单',
            type: 'warning'
          })
          return
        }
      }

      // 导出账单为同币种
      let currencyType = this.selection[0].currencyType
      for (let i = 0; i < this.selection.length; i++) {
        if (this.selection[i].currencyType != currencyType) {
          this.$message({
            showClose: true,
            message: '请选择同币种的账单',
            type: 'warning'
          })
          return
        }
      }


      this.$downloadFile({
        loading: true,
        type: 'json',
        url: '/fms-api/customer/CustomerBillRpc/exportBillExcel.json',
        data: {
          billIds: this.selection.map(it => it.id),
          billType: productType,
          ...this.getSuperTablePage().getSearchFormData()
        },
      })
    },

  }
};

</script>
<style>
.small-btn span {
  font-size: 14px;
}

.small-btn .el-button--small span {
  font-size: 14px;
}
</style>
